package com.guoliang.mailService.service.impl;

import com.guoliang.mailService.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author ：Leo
 * @date ：Created in 2023/1/27 10:38
 * @description：
 */
@Service
public class MailServiceImpl implements MailService {
   @Autowired
   private JavaMailSender sender;
   @Autowired
   private RedisTemplate<String,String> redisTemplate;
    @Value("${spring.mail.username}")
    private String email;
    @Override
    public void sendVerifyCode(String mail) {

        SimpleMailMessage message = new SimpleMailMessage();
        //邮件标题
        message.setSubject("【乐趣在线】您好，欢迎您注册乐趣在线");
        //设置随机数作为验证码
        Random random = new Random();
        String code = redisTemplate.opsForValue().get(mail);
        if (StringUtils.isEmpty(code)) code= String.valueOf(random.nextInt(89999) + 10000);
        //邮件内容
        message.setText("您的验证码是："+code+"，五分钟有效，请及时完成注册。若不是本人操作请忽略");
        //谁发送，必须和配置文件中的账号一致
        message.setFrom(email);
        //谁接收
        message.setTo(mail);
        sender.send(message);
        redisTemplate.opsForValue().set(mail,code,5, TimeUnit.MINUTES);
    }
}
